package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.JobFavoriteDTO;
import com.example.joblinker.dto.ResumeViewDTO;
import com.example.joblinker.dto.UserTodoDTO;
import com.example.joblinker.entity.Job;
import com.example.joblinker.entity.JobApplication;
import com.example.joblinker.entity.JobFavorite;
import com.example.joblinker.entity.Resume;
import com.example.joblinker.entity.ResumeView;
import com.example.joblinker.entity.UserTodo;
import com.example.joblinker.mapper.JobApplicationMapper;
import com.example.joblinker.mapper.JobFavoriteMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.mapper.ResumeMapper;
import com.example.joblinker.mapper.ResumeViewMapper;
import com.example.joblinker.mapper.UserTodoMapper;
import com.example.joblinker.service.PersonalService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 个人中心服务实现类
 */
@Service
public class PersonalServiceImpl implements PersonalService {

    @Resource
    private JobApplicationMapper jobApplicationMapper;

    @Resource
    private JobFavoriteMapper jobFavoriteMapper;

    @Resource
    private ResumeViewMapper resumeViewMapper;

    @Resource
    private UserTodoMapper userTodoMapper;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private ResumeMapper resumeMapper;

    @Override
    public Map<String, Integer> getUserStats(Long userId) {
        Map<String, Integer> stats = new HashMap<>();
        
        // 查询申请记录数
        LambdaQueryWrapper<JobApplication> applicationWrapper = new LambdaQueryWrapper<>();
        applicationWrapper.eq(JobApplication::getUserId, userId);
        int applicationCount = jobApplicationMapper.selectCount(applicationWrapper).intValue();
        stats.put("applicationCount", applicationCount);
        
        // 查询收藏职位数
        LambdaQueryWrapper<JobFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
        favoriteWrapper.eq(JobFavorite::getUserId, userId);
        int favoriteCount = jobFavoriteMapper.selectCount(favoriteWrapper).intValue();
        stats.put("favoriteCount", favoriteCount);
        
        // 查询简历被查看次数
        // 先查询用户所有简历
        LambdaQueryWrapper<Resume> resumeWrapper = new LambdaQueryWrapper<>();
        resumeWrapper.eq(Resume::getUserId, userId);
        List<Resume> resumes = resumeMapper.selectList(resumeWrapper);
        
        // 统计所有简历被查看次数
        int viewCount = 0;
        if (!resumes.isEmpty()) {
            List<Long> resumeIds = resumes.stream().map(Resume::getId).collect(Collectors.toList());
            LambdaQueryWrapper<ResumeView> viewWrapper = new LambdaQueryWrapper<>();
            viewWrapper.in(ResumeView::getResumeId, resumeIds);
            viewCount = resumeViewMapper.selectCount(viewWrapper).intValue();
        }
        stats.put("resumeViewCount", viewCount);
        
        // 查询待办事项数
        LambdaQueryWrapper<UserTodo> todoWrapper = new LambdaQueryWrapper<>();
        todoWrapper.eq(UserTodo::getUserId, userId)
                  .eq(UserTodo::getStatus, "pending");
        int todoCount = userTodoMapper.selectCount(todoWrapper).intValue();
        stats.put("todoCount", todoCount);
        
        return stats;
    }

    @Override
    public List<UserTodoDTO> getUserTodos(Long userId, Integer limit) {
        // 构建查询条件
        LambdaQueryWrapper<UserTodo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserTodo::getUserId, userId)
              .eq(UserTodo::getStatus, "pending")
              .orderByDesc(UserTodo::getUrgent)
              .orderByDesc(UserTodo::getCreateTime)
              .last(limit != null, "LIMIT " + limit);
        
        List<UserTodo> todos = userTodoMapper.selectList(wrapper);
        
        // 转换为DTO
        return todos.stream().map(todo -> {
            UserTodoDTO dto = new UserTodoDTO();
            BeanUtils.copyProperties(todo, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public Page<Map<String, Object>> getRecommendJobs(Long userId, Integer page, Integer size) {
        // 获取用户简历信息，用于推荐
        LambdaQueryWrapper<Resume> resumeWrapper = new LambdaQueryWrapper<>();
        resumeWrapper.eq(Resume::getUserId, userId)
                   .eq(Resume::getIsDefault, 1);
        Resume resume = resumeMapper.selectOne(resumeWrapper);
        
        // 构建职位查询条件
        Page<Job> pageParams = new Page<>(page, size);
        LambdaQueryWrapper<Job> jobWrapper = new LambdaQueryWrapper<>();
        
        // 如果有简历，根据简历信息过滤职位
        if (resume != null && resume.getJobTitle() != null) {
            jobWrapper.like(Job::getTitle, resume.getJobTitle())
                     .or()
                     .like(Job::getTags, resume.getJobTitle());
        }
        
        // 按创建时间倒序排序
        jobWrapper.orderByDesc(Job::getCreateTime);
        
        // 执行查询
        Page<Job> jobPage = jobMapper.selectPage(pageParams, jobWrapper);
        
        // 转换结果
        Page<Map<String, Object>> resultPage = new Page<>();
        BeanUtils.copyProperties(jobPage, resultPage, "records");
        
        List<Map<String, Object>> records = new ArrayList<>();
        for (Job job : jobPage.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", job.getId());
            map.put("title", job.getTitle());
            map.put("companyName", job.getCompanyName());
            map.put("companyLogo", job.getCompanyLogo());
            map.put("salary", job.getSalary());
            map.put("city", job.getCity());
            map.put("experience", job.getExperience());
            map.put("education", job.getEducation());
            map.put("createTime", job.getCreateTime());
            records.add(map);
        }
        
        resultPage.setRecords(records);
        return resultPage;
    }

    @Override
    public Page<JobFavoriteDTO> getFavoriteJobs(Long userId, String keyword, Integer page, Integer size) {
        // 构建查询条件
        Page<JobFavorite> pageParams = new Page<>(page, size);
        LambdaQueryWrapper<JobFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JobFavorite::getUserId, userId)
              .orderByDesc(JobFavorite::getCreateTime);
        
        // 执行查询
        Page<JobFavorite> favoritePage = jobFavoriteMapper.selectPage(pageParams, wrapper);
        
        // 转换结果
        Page<JobFavoriteDTO> resultPage = new Page<>();
        BeanUtils.copyProperties(favoritePage, resultPage, "records");
        
        List<JobFavoriteDTO> records = new ArrayList<>();
        for (JobFavorite favorite : favoritePage.getRecords()) {
            // 查询职位信息
            Job job = jobMapper.selectById(favorite.getJobId());
            if (job != null) {
                // 如果有关键词搜索，过滤不匹配的职位
                if (keyword != null && !keyword.isEmpty() && 
                    !job.getTitle().contains(keyword) && 
                    !job.getCompanyName().contains(keyword)) {
                    continue;
                }
                
                JobFavoriteDTO dto = new JobFavoriteDTO();
                dto.setUserId(favorite.getUserId());
                dto.setJobId(favorite.getJobId());
                dto.setCreateTime(favorite.getCreateTime());
                dto.setJobTitle(job.getTitle());
                dto.setCompanyName(job.getCompanyName());
                dto.setCompanyLogo(job.getCompanyLogo());
                dto.setSalary(job.getSalary());
                dto.setCity(job.getCity());
                dto.setExperience(job.getExperience());
                dto.setEducation(job.getEducation());
                records.add(dto);
            }
        }
        
        resultPage.setRecords(records);
        return resultPage;
    }

    @Override
    public boolean addFavoriteJob(Long userId, Long jobId) {
        // 检查职位是否存在
        Job job = jobMapper.selectById(jobId);
        if (job == null) {
            return false;
        }
        
        // 检查是否已收藏
        LambdaQueryWrapper<JobFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JobFavorite::getUserId, userId)
              .eq(JobFavorite::getJobId, jobId);
        Integer count = jobFavoriteMapper.selectCount(wrapper).intValue();
        if (count > 0) {
            return true; // 已收藏
        }
        
        // 添加收藏
        JobFavorite favorite = new JobFavorite();
        favorite.setUserId(userId);
        favorite.setJobId(jobId);
        favorite.setCreateTime(LocalDateTime.now());
        
        return jobFavoriteMapper.insert(favorite) > 0;
    }

    @Override
    public boolean removeFavoriteJob(Long userId, Long jobId) {
        LambdaQueryWrapper<JobFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JobFavorite::getUserId, userId)
              .eq(JobFavorite::getJobId, jobId);
        
        return jobFavoriteMapper.delete(wrapper) > 0;
    }

    @Override
    public Page<ResumeViewDTO> getResumeViews(Long userId, Integer page, Integer size) {
        // 先查询用户所有简历
        LambdaQueryWrapper<Resume> resumeWrapper = new LambdaQueryWrapper<>();
        resumeWrapper.eq(Resume::getUserId, userId);
        List<Resume> resumes = resumeMapper.selectList(resumeWrapper);
        
        if (resumes.isEmpty()) {
            return new Page<>(page, size, 0);
        }
        
        // 获取所有简历ID
        List<Long> resumeIds = resumes.stream().map(Resume::getId).collect(Collectors.toList());
        
        // 查询简历查看记录
        Page<ResumeView> pageParams = new Page<>(page, size);
        LambdaQueryWrapper<ResumeView> viewWrapper = new LambdaQueryWrapper<>();
        viewWrapper.in(ResumeView::getResumeId, resumeIds)
                  .orderByDesc(ResumeView::getViewTime);
        
        // 执行查询
        Page<ResumeView> viewPage = resumeViewMapper.selectPage(pageParams, viewWrapper);
        
        // 转换结果
        Page<ResumeViewDTO> resultPage = new Page<>();
        BeanUtils.copyProperties(viewPage, resultPage, "records");
        
        // 准备简历映射，方便快速查找
        Map<Long, Resume> resumeMap = resumes.stream()
                .collect(Collectors.toMap(Resume::getId, resume -> resume));
        
        List<ResumeViewDTO> records = new ArrayList<>();
        for (ResumeView view : viewPage.getRecords()) {
            ResumeViewDTO dto = new ResumeViewDTO();
            BeanUtils.copyProperties(view, dto);
            
            // 设置简历名称
            Resume resume = resumeMap.get(view.getResumeId());
            if (resume != null) {
                dto.setResumeName(resume.getName());
            }
            
            records.add(dto);
        }
        
        resultPage.setRecords(records);
        return resultPage;
    }
} 